//动态配置表单工具类
import { form } from './formValidation.js';
import { tableModelUrl } from './urlUtil.js';
let zMap,rMap = {}

/**
 * 表单主表data属性赋初始值
 * @param {Object} customData 非公用属性
 */
const buildFormData = function(customData) {
	if (!customData) {
		customData = {}
	}
	return Object.assign({
		edit: false,//保存修改标识
		checkedit: false,//审核修改标识
		menuName: '',//菜单名称
		busCode: '',//表单编码
		formdata: {},//表单提交数据
		mainConfigData: [],//主表配置数据
		subConfigData: {},//子表配置对象，key值为TableItem的fieldId
		initValue: {},//额外提交的属性，此处可以做初始化
		subEditorObj: {},//子表编辑器对象，key值为TableItem的fieldId
		uploadFileList:''  //文件上传
	}, customData)
}

/**
 * 表单子表data属性赋初始值
 * @param {Object} customData 非公用属性
 */
const buildSubFormData = function(customData) {
	if (!customData) {
		customData = {}
	}
	return Object.assign({
		edit:false,
		checkedit:false,
		initValue:{},
		autoformdata: [],//子表配置数据
		cachename:'',//子表的缓存名
		index:null,//子表数据索引
		datas:[],//同一子表所有记录
		order:0,//子表排序号
		formdata:{}
	}, customData)
}


const zuserAuthMap =  function(code){
	let pages = getCurrentPages();
	let _that = pages[pages.length - 1];
	//#ifdef APP-PLUS
	_that = _that['$vm']
	//#endif
	return _that.om.request(
		'/formFieldAuth/zuserAuthMap',
		{
			formCode:code
		}
	)
}

/**
 * 初始加载表单的ajax封装
 * @param {Object} ajaxArr 数组对象 [{url:"",param:{},method:"post"}]
 * @param {function} successFunc 成功回调函数
 * @param {Object} options 页面初始加载参数
 */
const formModelLoad = function(ajaxArr, successFunc, options) {
	let pages = getCurrentPages();
	let _that = pages[pages.length - 1];
	//#ifdef APP-PLUS
	_that = _that['$vm']
	//#endif
	if(options){
		_that.menuName = options.title;
		uni.setNavigationBarTitle({
			title: _that.menuName
		});
		formShowLoading(_that)
		_that.busCode = options.code;
		if (options.checkedit) {
			if (typeof(options.checkedit) == 'string') {
				if (options.checkedit == "true") {
					_that.checkedit = true
				}
			} else {
				_that.checkedit = options.checkedit
			}
		} else if (options.edit) {
			if (typeof(options.edit) == 'string') {
				if (options.edit == "true") {
					_that.edit = true
				}
			} else {
				_that.edit = options.edit
			}
		}
	}
	
	if (!_that.busCode) {
		return;
	}
	if (!ajaxArr) {
		ajaxArr = []
	}
	if(_that.checkedit){
		ajaxArr.push({
			url:"formFieldToFlowNode/getCheckListByFileId",
			param:{
				busCode: _that.busCode,
				fileId: options.fileId
			}
		})
	}
	ajaxArr.push(tableModelUrl(_that.busCode))
	let arr = []
	ajaxArr.forEach(e => {
		arr.push(_that.om.request(e.url, e.param || {}, e.method || "get"))
	})
	//多个AJAX全部完成时开始执行
	Promise.all(arr).then(async res => {
		if (res[res.length - 1].succeed) {
			let data = res[res.length - 1].value;
			let checkeditData;
			if(_that.checkedit){
				if(res[res.length - 2].succeed){
					checkeditData = res[res.length - 2].value;
				}
			}
			if(res[res.length - 1].succeed){
				_that.ismenu = res[res.length - 1].value.ismenu
			}
			if(_that.edit || _that.checkedit){
				_that.ismenu = false
			}
			if(data.hasLookAuth){
				zMap = await zuserAuthMap(_that.busCode).then(mres=>{ return mres.value})
				rMap = data.realLookAuthMap
			}
			let mainData = configFormEditor(data, checkeditData,_that.checkedit)
			//抄送人
			changeEditor('bottominfo', 'formUserIds','isSearchUser', true, mainData);
			changeEditor("bottominfo", "formUserIds", "link", "/pages/public/searchUser/searchUser?isFormUser=true", mainData)
			changeEditor("bottominfo", "formUserIds",{
				'linkParam':{
					isNew:true,
					defaultDataCache:'defaultFormUserData'
				}
			},null,mainData)
			if (successFunc) {
				successFunc(res, mainData)
			}
			if (_that.$refs.autoform) {
				_that.$refs.autoform.configData = mainData;
			}
		}
	})
}


const setSubmitSubValue = function() {
	let pages = getCurrentPages();
	let _that = pages[pages.length - 1];
	//#ifdef APP-PLUS
	_that = _that.$vm
	//#endif
	if (_that.subEditorObj) {
		for (let fieldId in _that.subEditorObj) {
			let editor = _that.subEditorObj[fieldId]
			if (editor.workList.length) {
				let str = JSON.stringify(editor.workList);
				_that.formdata[editor.valueField] = str
				if(_that.$refs.autoform){
					_that.$refs.autoform.formdata[editor.valueField] = str
				}
			}else{
				_that.formdata[editor.valueField] = "[]"
				if(_that.$refs.autoform){
					_that.$refs.autoform.formdata[editor.valueField] = "[]"
				}
			}
		}
	}
}

const configFormEditor = function(data, checkeditData,checkedit) {
	let pages = getCurrentPages();
	let _that = pages[pages.length - 1];
	let mainData = [];
	if (data.top) {
		mainData.push({
			key: 'topinfo',
			editors: tranferToEditors(data.top, checkeditData,checkedit)
		})
	}

	if (data.bodyTitle.length > 0) {
		for (let i = 0; i < data.bodyTitle.length; i++) {
			let datas = (data['body' + i] || []);
			if (data.bodyTitle[i].iswxAddShow && (data.bodyTitle[i].issub || data.bodyTitle[i].fieldId =='title_chart' )) {
				//#ifdef APP-PLUS
				if (!_that.subConfigData) {
					_that = _that.$vm;
				}
				//#endif
				if (!_that.subConfigData) {
					continue
				}
				_that.subConfigData[data.bodyTitle[i].fieldId] = [{
					title: data.bodyTitle[i].itemName,
					key: data.bodyTitle[i].fieldId,
					issub: true,
					editors: tranferToEditors(datas,checkeditData,checkedit)
				}]
				let editors = tranferToEditors([data.bodyTitle[i]], checkeditData,checkedit)
				if(!editors.length){
					continue
				}
				editors[0].hasSubToolbarOnCheck = data.bodyTitle[i].hasSubToolbarOnCheck
				editors[0].groupKey = data.bodyTitle[i].fieldId
				editors[0].link = "data-info-" + data.bodyTitle[i].fieldId
				editors[0].workConfigDataCacheKey = getWorkConfigDataCacheKey(data.bodyTitle[i].fieldId)
				editors[0].workCacheKey = getWorkCacheKey(data.bodyTitle[i].fieldId);
				editors[0].workList = []
				mainData.push({
					title: data.bodyTitle[i].itemName,
					key: data.bodyTitle[i].fieldId,
					collapse: data.bodyTitle[i].collapse,
					editors: editors
				});
				if (_that.subEditorObj) {
					_that.subEditorObj[data.bodyTitle[i].fieldId] = editors[0]
				}
			} else {
				if (data.bodyTitle[i].wxbox) {
					mainData.push({
						title: data.bodyTitle[i].itemName,
						key: data.bodyTitle[i].fieldId,
						collapse: data.bodyTitle[i].collapse,
						editors: tranferToEditors([data.bodyTitle[i]], checkeditData,checkedit)
					});
				} else {
					mainData.push({
						title: data.bodyTitle[i].itemName,
						key: data.bodyTitle[i].fieldId,
						collapse: data.bodyTitle[i].collapse,
						editors: tranferToEditors(datas, checkeditData,checkedit)
					});
				}

			}
		}
	}
	if (data.bottom) {
		mainData.push({
			key: 'bottominfo',
			editors: tranferToEditors(data.bottom, checkeditData,checkedit)
		})
	}
	return mainData;
}
/**
 * 获取
 * @param {Object} _that
 * @param {Object} fileId
 */
const getWorkConfigDataCacheKey = function(fieldId, _that) {
	if (!_that) {
		let pages = getCurrentPages();
		_that = pages[pages.length - 1];
	}
	
	//#ifdef APP-PLUS
	return _that.$page.route.replace(new RegExp("/","gm"),"-") + "-work-config-data-" + fieldId
	//#endif
	//#ifndef APP-PLUS
	return _that.$page.meta.name + "-work-config-data-" + fieldId
	//#endif
}

const getWorkCacheKey = function(fieldId, _that) {
	if (!_that) {
		let pages = getCurrentPages();
		_that = pages[pages.length - 1];
	}
	
	//#ifdef APP-PLUS
	return _that.$page.route.replace(new RegExp("/","gm"),"-") + "-work-" + fieldId
	//#endif
	//#ifndef APP-PLUS
	return _that.$page.meta.name + "-work-" + fieldId
	//#endif
}

/**
 * 获取编辑器标题
 * @param {Object} key
 * @param {Object} valueField
 * @param {Object} configData
 */
const getEditorTitle = function(key, valueField, configData){
	let arr = configData.filter(e => e.key == key)
	let title = ""
	if (arr && arr.length) {
		arr.forEach(e => {
			for (let i = 0; i < e.editors.length; i++) {
				let editor = e.editors[i]
				if (editor.valueField == valueField) {
					title = editor.title
				}
			}
		})
	}
	return title
}

const getEditor = function(key, valueField, configData){
	let arr = configData.filter(e => e.key == key)
	let obj = {}
	if (arr && arr.length) {
		arr.forEach(e => {
			for (let i = 0; i < e.editors.length; i++) {
				let editor = e.editors[i]
				if (editor.valueField == valueField) {
					obj = editor
				}
			}
		})
	}
	return obj
}

const hasEditor = function(key, valueField, configData){
	let arr = configData.filter(e => e.key == key)
	let title = ""
	if (arr && arr.length) {
		for(let k=0;k<arr.length;k++){
			let e = arr[k]
			for (let i = 0; i < e.editors.length; i++) {
				let editor = e.editors[i]
				if (editor.valueField == valueField) {
					return true
				}
			}
		}
	}
	return false
}

/**
 * 配置组属性赋值
 * @param {Object} key 分组key值
 * @param {Object} configKey 配置项的key
 * @param {Object} newValue   新值
 */
const changeConfigAttr = function(key, configKey, newValue, configData) {
	let arr = configData.filter(e => e.key == key);
	if (arr && arr.length) {
		arr.forEach(e => {
			e[configKey] = newValue
		})
	}
}


/**
 * 改变编辑器指定属性值
 * 
 * @param {Object} k 一组编辑器对象或分组fieldId
 * @param {Object} valueField 要查找的编辑器的value
 * @param {Object} editorKey 改变组件属性的key 或者 改变一组属性请传对象{data:[],valueField:"id"},将忽略newValue
 * @param {Object} newValue 新值或为null
 * @param {Object} configData 表单配置数组对象
 */
const changeEditor = function(k, valueField, editorKey, newValue, configData) {
	//if (k instanceof Array) {
	if(Object.prototype.toString.call(k)==='[object Array]'){
		for (let i = 0; i < k.length; i++) {
			let editor = k[i]
			if (editor.valueField == valueField) {
				if (typeof(editorKey) == 'string') {
					editor[editorKey] = newValue
				//} else if (editorKey instanceof Object) {
				} else if (Object.prototype.toString.call(editorKey)==='[object Object]') {
					for (let e in editorKey) {
						editor[e] = editorKey[e]
					}
				}
				break
			}
		}
	} else if (typeof(k) == "string") {
		let obj;
		//if (editorKey instanceof Object) {
		if (Object.prototype.toString.call(editorKey)==='[object Object]') {
			obj = (newValue || configData)
		}else{
			obj = configData
		}
		//if (obj && obj instanceof Array) {
		if (obj && Object.prototype.toString.call(obj)==='[object Array]') {
			let arr = obj.filter(e => e.key == k)
			if (arr && arr.length) {
				arr.forEach(e => {
					for (let i = 0; i < e.editors.length; i++) {
						let editor = e.editors[i]
						if (editor.valueField == valueField) {
							if (typeof(editorKey) == 'string') {
								editor[editorKey] = newValue
							//} else if (editorKey instanceof Object) {
							} else if (Object.prototype.toString.call(editorKey)==='[object Object]') {
								for (let e in editorKey) {
									editor[e] = editorKey[e]
								}
							}
							break
						}
					}
				})
			}

		}
	}

}

/**
 * 改变编辑器指定属性值
 * @param {Object} obj 传递this
 * @param {Object} editors 一组编辑器对象
 * @param {Object} valueField 要查找的编辑器的value
 * @param {Object} editorKey 改变组件属性的key 或者 改变一组属性请传对象{data:[],valueField:"id"},将忽略newValue
 * @param {Object} newValue 新值
 */
const autoChangeEditor = function(param, editorParam) {
	let obj = param.obj
	let key = param.key
	let valueField = param.valueField
	if (obj && obj.$refs && obj.$refs.autoform) {
		obj.$refs.autoform.changeEditor(key, valueField, editorParam);
	} else {
		let editors = param.editors ? param.editors : obj.autoformdata[0].editors
		let configData = param.configData
		changeEditor(editors, valueField, editorParam, null, configData)
	}
}

/**
 * 配置下拉框备选数据
 * 
 * @param {Object} data 下拉框数据,数组
 * @param {Object} valueField 值字段,如"id"
 * @param {Object} nameField 名称字段,如"dicname"
 * @param {Boolean} ignoreSelect 忽略“请选择” 
 */
const configSelectData = function(data, valueField, nameField, ignoreSelect) {
	let configData = []
	if(!ignoreSelect){
		configData.push({
			text: "请选择"
		})
	}
	if (!data || !data.length) {
		return configData
	}
	data.forEach(e => {
		configData.push({
			value: e[valueField],
			text: e[nameField],
			attr: e
		})
	})
	return configData
}

const hasChildren = function(data,num,subArr,valueField, nameField){
	let arr = []
	for(let item of data){
		if(item.children && item.children.length){
			arr = hasChildren(item.children,num+1,subArr,valueField, nameField)
		}else{
			arr.push({
				value: item[valueField],
				text: item[nameField],
				children:item.children,
				attr:item
			})
		}
	}
	if(arr.length){
		subArr.push(arr)
	}
	return subArr
}

const configMultiSelectData = function(data, valueField, nameField) {
	let configData = []
	let arr = []
	let layer = 2
	let subArr = []
	for(let i in data){
		if(i == 0){
			subArr = hasChildren(data[i].children,0,new Array(), valueField, nameField)	
		}
		if((subArr.length + 1)>layer){
			layer = subArr.length
		}
		if(data[i].children.length){
			arr.push({
				value: data[i][valueField],
				text: data[i][nameField],
				children:data[i].children,
				attr:data[i]
			})
		}
	}
	configData.push(arr)
	for (let i = 0; i <(layer-1);i++) {       
	    configData.push(subArr[i])
	}
	return configData
}


/**
 * 子表的onLoad公用方法
 * @param {Object} _that 	当前操作页面的vue对象
 * @param {Object} e 		页面传参
 * @param {Object} initLoad 初始加载方法
 */
const subOnLoad = function(_that, e, initLoad,ajaxArr) {
	let index = e.index
	if (e.checkedit) {
		if (typeof(e.checkedit) == 'string') {
			if (e.checkedit == "true") {
				_that.checkedit = true
			}
		} else {
			_that.checkedit = e.checkedit
		}
	} else if (e.edit) {
		if (typeof(e.edit) == 'string') {
			if (e.edit == "true") {
				_that.edit = true
			}
		} else {
			_that.edit = e.edit
		}
	}
	if(e.groupKey){
		_that.groupKey = e.groupKey
	}
	if (e.cachename) {
		_that.cachename = e.cachename
		uni.getStorage({
			key: _that.cachename,
			success: function(res) {
				if (res.data && res.data.length) {
					_that.datas = res.data
					if (hasValue(index) && index != "") {
						let d = res.data[index]
						for (let i in d) {
							if(Object.prototype.toString.call(d[i]) == '[object Number]'){
								_that.$set(_that.formdata, i, d[i] || 0)
							}else{
								_that.$set(_that.formdata, i, d[i] || "")
							}
						}
						_that.order = parseInt(index) + 1
						_that.index = parseInt(index)
					} else {
						_that.order = res.data.length + 1
					}
				} else {
					_that.order = 1
				}
				uni.removeStorage({
					key:_that.cachename
				})
				if(ajaxArr){
					let arr = []
					ajaxArr.forEach(e => {
						arr.push(_that.om.request(e.url, e.param || {}, e.method || "get"))
					})
					Promise.all(arr).then(async res => {
						if (initLoad) {
							if (typeof(initLoad) == 'string') {
								_that[initLoad]
							} else if (typeof(initLoad) == 'function') {
								initLoad(res)
							}
						}
					})
				}else{
					if (initLoad) {
						if (typeof(initLoad) == 'string') {
							_that[initLoad]
						} else if (typeof(initLoad) == 'function') {
							initLoad()
						}
					}
				}
				
			},
			fail() {
				_that.order = 1
				if(ajaxArr){
					let arr = []
					ajaxArr.forEach(e => {
						arr.push(_that.om.request(e.url, e.param || {}, e.method || "get"))
					})
					Promise.all(arr).then(async res => {
						if (initLoad) {
							if (typeof(initLoad) == 'string') {
								_that[initLoad]
							} else if (typeof(initLoad) == 'function') {
								initLoad(res)
							}
						}
					})
				}else{
					if (initLoad) {
						if (typeof(initLoad) == 'string') {
							_that[initLoad]
						} else if (typeof(initLoad) == 'function') {
							initLoad()
						}
					}
				}
			}
		});
	} else {
		uni.navigateBack({

		})
	}
}
/**
 * 动态配置表单验证
 * @param {Object} configData 表单配置数据 
 * @param {Object} formdata   表单提交数据
 */
const formValidation = function(configData, formdata) {
	let rules = [];
	configData.forEach(sub => {
		sub.editors.forEach(el => {
			let rule = []
			let msg = []
			if (el.required && !el.necessaryBeforeSend) {
				rule.push("required")
				switch (el.type) {
					case "imagebox":
						break;
					case "textbox":
					case "textarea":
					case "numberbox":
						msg.push("请输入" + el.title)
						break;
					default:
						msg.push("请选择" + el.title)
						break;
				}
			}
			if (el.type == "numberbox") {
				if (hasValue(el.min,true) && hasValue(el.max,true)) {
					rule.push("range:[" + el.min + "," + el.max + "]")
					msg.push(el.title + "应介于" + el.min + "与" + el.max + "之间")
				}
			}
			if (el.rules && el.rules.length) {
				el.rules.forEach(r => {
					let ruleItem = r;
					//数据处理
					let value = null;
					if (~ruleItem.indexOf(":")) {
						let temp = ruleItem.split(":");
						ruleItem = temp[0];
						value = temp[1];
					}
					rule.push(r)
					switch (ruleItem) {
						case "isEnAndNo":
							msg.push(el.title + "格式为英文字母和数字")
							break;
						case "isSame":
							msg.push(el.title + "输入错误")
							break;
						case "minLength":
							msg.push(el.title + "的输入长度应不少于" + value)
							break;
						case "maxLength":
							msg.push(el.title + "的输入长度应不超过" + value)
							break;
						default:
							msg.push(el.title + "格式错误")
					}
				})
			}
			if (rule.length) {
				rules.push({
					name: el.valueField,
					rule: rule,
					msg: msg
				})
			}
		})
	})
	return form.validation(formdata, rules);
}

const verifyDataList = function(dataList, configData, ms_title) {
	if (!dataList || !dataList.length) {
		return ('请配置' + ms_title);
	}
	for (let i = 0; i < dataList.length; i++) {
		let checkRes = formValidation(configData, dataList[i])
		if (checkRes) {
			return ("第" + (i + 1) + "条" + ms_title + "：" + checkRes)
		}
	}
	return true
}

const canShowBEditor = function(config){
	let rArr = Object.keys(rMap)
	if(config.fieldId == 'sumCosts'){
		let _that = config
	}
	if(rArr.length == 0){
		return true
	}
	let ed = rMap[config.tableItemId]
	if(ed){
		let zArr = Object.keys(zMap)
		if(zArr.length == 0){
			return false
		}
		let editor = zMap[config.tableItemId]
		if(editor){
			return true
		}
	}else{
		return true
	}
	
}

/**
 * 获取表单头信息
 * 
 * @param {Object} origData 服务器查询到的原始数据
 */
var tranferToEditors = function(origData, checkeditData,checkedit) {
	var editors = []
	if (origData.length) {
		for (var i = 0; i < origData.length; i++) {
			var config = origData[i];
			if (!config.iswxAddShow) {
				continue
			}
			var checkeditConfig;
			if(checkeditData){
				checkeditConfig = checkeditData[config.tableItemId]
			}
			var editor = {}
			if(!checkedit){
				if(canShowBEditor(config)){
					editor = tranferEditor(config, checkeditConfig);
				}else{
					continue
				}
			}else{
				editor = tranferEditor(config, checkeditConfig);
			}
			if (editor != null) {
				editors.push(editor)
			}
		}
	}
	return editors;
}

var hasValue = function(value, verifyEmptyString) {
	if (value != null && value != undefined) {
		if(verifyEmptyString){
			return value !== ""
		}
		return true
	}
	return false
}

/**
 * 单个控件转化为单个表单元素配置对象
 * @param {Object} config          数据格式参考服务器代码{TableResponse}
 * @param {Object} checkeditConfig 数据格式参考服务器代码{FormFieldToFlowNode}
 */
const tranferEditor = function(config, checkeditConfig) {
	let _that
	if (config.onlyCheckedit) {
		let pages = getCurrentPages();
		_that = pages[pages.length - 1];
		//#ifdef APP-PLUS
		_that = _that['$vm'];
		//#endif
		if (!_that.checkedit) { //非审核修改时，不显示
			return null
		}
	}

	if (!config.wxbox) {
		return null;
	}
	
	let editor = {
		formFieldId:config.tableItemId,
		type: config.wxbox,
		title: config.itemName,
		valueField: config.fieldName || config.fieldId,
		required: checkeditConfig?checkeditConfig.editNecessary:(_that?false:config.isnecessary) ,
		nameField: config.fieldText, 
		checkedit: checkeditConfig ? checkeditConfig.canEdit: false,
		isfull: config.isfull,
		editReadonly: config.editReadonly,
		necessaryBeforeSend:config.necessaryBeforeSend
	}
	
	if (config.defaultValue) {
		editor.defaultValue = config.defaultValue
	}
	if (config.rules) {
		editor.rules = config.rules.split(',')
	}
	if (config.verifyFunc) {
		editor.verifyfunc = config.verifyFunc
	}
	if (config.onSelect) {
		editor.onSelect = config.onSelect
	}
	if (config.clearFunc) {
		editor.clearFunc = config.clearFunc
	}
	if (config.prefix) {
		editor.prefix = config.prefix
	}
	if (config.suffix) {
		editor.suffix = config.suffix
	}
	if (hasValue(config.min)) {
		editor.min = config.min
	}
	if (hasValue(config.max)) {
		editor.max = config.max
	}
	if (hasValue(config.wordNumber) && !editor.type == 'numberbox') {
		editor.max = config.wordNumber
	}
	if (hasValue(config.precision)) {
		editor.precision = config.precision
		editor.digit = true
	}
	switch (config.wxbox) {
		case "labelbox":
			editor.required = false
			break
		case "textbox":
			editor.prompt = "请输入"
			break
		case "editlinkbox":
		case "textarea":
			if(config.wordNumber){
				editor.max = config.wordNumber
			}
			editor.prompt = "请点击输入"
			break
		case "editselectbox":
			editor.data = []
			if (hasValue(config.min) && hasValue(config.max)) {
				editor.prompt = "字数介于" + config.min + "~" + config.max + "之间"
				break
			}
			if (hasValue(config.min)) {
				editor.prompt = "字数不少于" + config.min
				break
			}
			if (hasValue(config.max)) {
				editor.prompt = "字数不超过" + config.max
				break
			}
			editor.prompt = "请选择或输入"
			break
		case "numberbox":
			if (hasValue(config.min, true) && hasValue(config.max, true)) {
				editor.prompt = "介于" + config.min + "~" + config.max + "之间"
				break
			}
			if (hasValue(config.min,true)) {
				editor.prompt = "不小于" + config.min
				break
			}
			if (hasValue(config.max,true)) {
				editor.prompt = "不大于" + config.max
				break
			}
			editor.precisionField = config.precisionField
			editor.prompt = "请输入"
			break
		case "checkbox":
			editor.data = []
			break
		case "switchbox":
		if(!config.fieldName && config.fieldText){
			editor.valueField = config.fieldText
		}
			editor.required = false
			break
		case "datebox":
			editor.prompt = "请选择"
			if (editor.min) {
				let arr = editor.min.split(':');
				if (arr.length < 2) {
					editor.startField = editor.min
					editor.min = null
				}
			}
			if (editor.max) {
				let arr = editor.max.split(':');
				if (arr.length < 2) {
					editor.endField = editor.max
					editor.max = null
				}
			}
			break
		case "timebox":
			editor.prompt = "请选择"
			if (editor.min) {
				let arr = editor.min.split('-');
				if (arr.length < 3) {
					editor.startField = editor.min
					editor.min = null
				}
			}
			if (editor.max) {
				let arr = editor.max.split('-');
				if (arr.length < 3) {
					editor.endField = editor.max
					editor.max = null
				}
			}
			break
		case "datetimebox":
		case "selectbox":
			editor.prompt = "请选择"
			editor.data = []
			break
		case "multiselectbox":
			editor.prompt = "请选择"
			editor.popupTitle = "列表信息"
			editor.data = []
			break
		case "linkbox":
			editor.prompt = "请选择"
			editor.link = config.link /* 跳转路径 */
			editor.linkParam = config.linkParam /* 跳转路径携带参数，对象{key:value} */
			break
		case "imagebox":
			editor.fileUrlList = []
			editor.tempFileList = []
			editor.defaultValue = []
			break
		case "lookfilebox":
			editor.fileList = []
			break
		case "subbox":
			editor.showAdd = true
			editor.showDel = true
			break
	}
	return editor
}

const formShowLoading = function(_that, cancelField) {
	var times = 0;
	uni.showLoading({

	})
	var interval = setInterval(function() {
		if (_that && _that[cancelField]) {
			clearInterval(interval)
			uni.hideLoading()
		} else if (times > 10) {
			clearInterval(interval)
			uni.hideLoading()
		} else {
			times++;
		}
	}, 500)
}

var getFormFields = function(configData) {
	var fieldArr = []
	configData.forEach(obj => {
		obj.editors.forEach(el => {
			if (el.nameField) {
				fieldArr.push(el.nameField)
			}
			if (el.valueField) {
				fieldArr.push(el.valueField)
			}
		});
	});
	return fieldArr
}

const insertAfterEditor = function(key,afterValueField,editor,configData){
	let editors = [];
	for(let i=0;i<configData.length;i++){
		if(configData[i].key == key){
			editors = configData[i].editors
			break;
		}
	}
	let insertIndex = -1;
	for(let i=0;i<editors.length;i++){
		let tempEditor = editors[i]
		if(tempEditor.valueField == afterValueField){
			insertIndex = i
			break
		}
	}
	if(~insertIndex){
		if(insertIndex + 1 < editors.length){
			editors.splice(insertIndex+1, 0, editor);
		}else{
			editors.push(editor)
		}
	}
}
/*
*替换分组标题下的内容
*/
const insertEditors = function(key,editors,configData){
	let oEditors = [];
	for(let i=0;i<configData.length;i++){
		if(configData[i].key == key){
			oEditors = configData[i].editors
			break;
		}
	}
	oEditors.length = 0;  
	oEditors.push(...editors)
}
/*
  改变树状数据为数组
*/
const changeTreeData = function(arr){
	let newArr = []
	for(let item of arr){
		newArr.push(item)
		if(item.children && item.children.length){
			let subArr = changeTreeData(item.children)
			if(subArr.length){
				newArr.push(...subArr)
			}
		}
	}
	return newArr 
}

const insertAfterEditorArr = function(key,afterValueField,editor,configData){
	let editors = [];
	for(let i=0;i<configData.length;i++){
		if(configData[i].key == key){
			editors = configData[i].editors
			break;
		}
	}
	let insertIndex = -1;
	for(let i=0;i<editors.length;i++){
		let tempEditor = editors[i]
		if(tempEditor.valueField == afterValueField){
			insertIndex = i
			break
		}
	}
	if(~insertIndex){
		if(insertIndex + 1 < editors.length){
			if(Object.prototype.toString.call(editor) == "[object Array]"){
				let num = insertIndex+1
				editor.unshift(num, 0); 
				Array.prototype.splice.apply(editors,editor); 
			}else{
				editors.splice(insertIndex+1, 0, editor);
			}
		}else{
			editors.push(editor)
		}
	}
}

export {
	buildFormData,
	buildSubFormData,
	changeEditor,
	autoChangeEditor,
	configSelectData,
	configMultiSelectData,
	subOnLoad,
	formValidation,
	tranferToEditors,
	hasValue,
	tranferEditor,
	formShowLoading,
	getFormFields,
	verifyDataList,
	configFormEditor,
	getWorkConfigDataCacheKey,
	getWorkCacheKey,
	setSubmitSubValue,
	changeConfigAttr,
	formModelLoad,
	getEditorTitle,
	hasEditor,
	getEditor,
	insertAfterEditor,
	insertEditors,
	changeTreeData,
	insertAfterEditorArr
}
